//                       .::::.
//                     .::::::::.
//                    :::::::::::
//                 ..:::::::::::'
//              '::::::::::::'
//                .::::::::::
//           '::::::::::::::..
//                ..::::::::::::.
//              ``::::::::::::::::
//               ::::``:::::::::'        .:::.
//              ::::'   ':::::'       .::::::::.
//            .::::'      ::::     .:::::::'::::.
//           .:::'       :::::  .:::::::::' ':::::.
//          .::'        :::::.:::::::::'      ':::::.
//         .::'         ::::::::::::::'         ``::::.
//     ...:::           ::::::::::::'              ``::.
//    ```` ':.          ':::::::::'                  ::::..
//                       '.:::::'                    ':'````..
package com.xw.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import com.xw.common.Const;
import com.xw.dao.*;
import com.xw.model.*;
import com.xw.util.AppUtil;
import com.xw.util.JsonData;
import com.xw.util.JsonUtil;
import com.xw.vo.UserInfoVo;
import com.xw.vo.VideosInfoVo;
import com.xw.vo.VideosItemVo;
import com.xw.vo.VideosVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
@Transactional(rollbackFor = Exception.class)
public class VideosServiceImpl implements VideosService {

    @Resource
    private VideosMapper videosMapper;
    @Resource
    private VideosItemMapper videosItemMapper;
    @Resource
    private VideosInfoMapper videosInfoMapper;
    @Resource
    private HistoryUploadVideosMapper uploadVideosMapper;
    @Resource
    private BuyVideosMapper buyVideosMapper;
    @Resource
    private SysUserInfoMapper userInfoMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private PlayRecordSonMapper playRecordSonMapper;

    @Override
    public Map getPassVideoItemNoVideos(String userId, Integer page, Integer limit) {
        if (page != null && limit != null){
            PageHelper.startPage(page,limit,false);
        }
        List<VideosItem> list = videosItemMapper.getPassVideoItemNoVideos(userId);
        return JsonData.success(list);
    }

    @Override
    public Map getCheckingAndPassVideo(String userId, Integer page, Integer limit) {
        List<VideosItem> videosItems;
        if (page != null && limit != null){
            PageHelper.startPage(page,limit,false);
        }

        PageHelper.orderBy("is_top desc,create_time desc");
        List<Videos> videosList = videosMapper.getCheckingAndPassVideo(userId);
        for (Videos videos : videosList){
            VideosItemVo videosItemVo = new VideosItemVo();
            videosItemVo.setVideoId(videos.getVideoId());
            videosItems = videosItemMapper.select(videosItemVo);
            Integer videoItemCount = videosItems.size();
            videos.setVideoItemCount(videoItemCount);
        }
        Integer videosListCount = this.videosMapper.getCheckingAndPassVideo(userId).size();
        Map map = Maps.newHashMap();
        map.put("videosList",videosList);
        map.put("videosListCount",videosListCount);
        return JsonData.success(map);
    }

    @Override
    public Map getCheckNoPassVideo(String userId, Integer page, Integer limit) {
        List<VideosItem> videosItems;
        if (page != null && limit != null){
            PageHelper.startPage(page,limit,false);
        }

        PageHelper.orderBy("is_top desc,create_time desc");
        List<Videos> videosList = videosMapper.getCheckNoPassVideo(userId);
        for (Videos videos : videosList){
            VideosItemVo videosItemVo = new VideosItemVo();
            videosItemVo.setVideoId(videos.getVideoId());
            videosItems = videosItemMapper.select(videosItemVo);
            Integer videoItemCount = videosItems.size();
            videos.setVideoItemCount(videoItemCount);
        }
        Integer videosListCount = this.videosMapper.getCheckNoPassVideo(userId).size();
        Map map = Maps.newHashMap();
        map.put("videosList",videosList);
        map.put("videosListCount",videosListCount);
        return JsonData.success(map);
    }

    @Override
    public Map getCheckPassVideo(String userId, Integer page, Integer limit) {
        List<VideosItem> videosItems;
        if (page != null && limit != null){
            PageHelper.startPage(page,limit,false);
        }

        PageHelper.orderBy("is_top desc,create_time desc");
        List<Videos> videosList = videosMapper.getCheckPassVideo(userId);
        for (Videos videos : videosList){
            VideosItemVo videosItemVo = new VideosItemVo();
            videosItemVo.setVideoId(videos.getVideoId());
            videosItems = videosItemMapper.select(videosItemVo);
            Integer videoItemCount = videosItems.size();
            videos.setVideoItemCount(videoItemCount);
        }
        Integer videosListCount = this.videosMapper.getCheckPassVideo(userId).size();
        Map map = Maps.newHashMap();
        map.put("videosList",videosList);
        map.put("videosListCount",videosListCount);
        return JsonData.success(map);
    }

    @Override
    public Map getCheckingVideo(String userId, Integer page, Integer limit) {
        List<VideosItem> videosItems;
        if (page != null && limit != null){
            PageHelper.startPage(page,limit,false);
        }

        PageHelper.orderBy("is_top desc,create_time desc");
        List<Videos> videosList = videosMapper.getCheckingVideo(userId);
        for (Videos videos : videosList){
            VideosItemVo videosItemVo = new VideosItemVo();
            videosItemVo.setVideoId(videos.getVideoId());
            videosItems = videosItemMapper.select(videosItemVo);
            Integer videoItemCount = videosItems.size();
            videos.setVideoItemCount(videoItemCount);
        }
        Integer videosListCount = this.videosMapper.getCheckingVideo(userId).size();
        Map map = Maps.newHashMap();
        map.put("videosList",videosList);
        map.put("videosListCount",videosListCount);
        return JsonData.success(map);
    }

    @Override
    public Map addStudyCount(String userId, String videoId) {
        Videos videos = videosMapper.selectByPrimaryKey(videoId);
        videos.setStudyCount(videos.getStudyCount() + 1);
        videosMapper.updateByPrimaryKeySelective(videos);
        return JsonData.success();
    }

    @Override
    public Map createVideo(String userId, String videoName, String teacherName, String stIdOne, String stIdTwo, String videoDesc, String videoImg, Integer isFree,
                           Double originalPrice, Double currentPrice, Integer publishType, String videosItemIds, String videosInfoJson) {
        /*创建课程*/
        Videos videos = new Videos();
        String videosId = AppUtil.uuid();
        videos.setVideoId(videosId);
        videos.setUserId(userId);
        videos.setVideoName(videoName);
        videos.setTeacherName(teacherName);
        videos.setStIdOne(stIdOne);
        videos.setStIdTwo(stIdTwo);
        videos.setVideoDesc(videoDesc);
        videos.setVideoImg(videoImg);
        videos.setIsFree(isFree);
        videos.setPublishType(publishType);
        videos.setIsPublish(0);
        videos.setUpdateTime(new Date());
        videos.setCreateId(userId);
        if (isFree == 0){
            //0.否 1.是
            videos.setOriginalPrice(originalPrice);
            videos.setCurrentPrice(currentPrice);
        }
        videos.setCreateTime(new Date());
        videosMapper.insertSelective(videos);
        /*将已发布的视频关联课程*/
        List<String> videoItemIdList = Splitter.on(",").splitToList(videosItemIds);
        videosItemMapper.relationVideosId(videosId,videoItemIdList);

        /*添加的资料*/
        if (StringUtils.isNotBlank(videosInfoJson)){
            List<VideosInfo> videosInfos = JsonUtil.string2Obj(videosInfoJson, new TypeReference<List<VideosInfo>>() {
            });
            if (CollectionUtils.isNotEmpty(videosInfos)){
                videosInfoMapper.insertBatch(videosInfos);
            }
        }

        return JsonData.success();
    }

    public static void main(String[] args) {
        VideosInfo info = new VideosInfo();
        info.setVideoId("3121356623");
        info.setVideoInfoName("课程资料名称");
        info.setVideoInfoSort(1);
        info.setVideoInfoUrl("课程资料链接");
        info.setCreateId("上传用户id");
        System.out.println(JsonUtil.obj2String(info));
    }

    @Override
    public Map setMyRecommendVideo(String userId, String videoId, Integer myRecommend) {
        Videos videos = videosMapper.selectByPrimaryKey(videoId);
        if (!StringUtils.equals(userId,videos.getUserId())){
            return JsonData.fail("只能操作自己的视频");
        }

        videos.setMyRecommend(myRecommend);
        videos.setMyRecommendTime(new Date());
        int i = videosMapper.updateByPrimaryKeySelective(videos);

        return JsonData.returnMap(i);
    }

    @Override
    public Map searchVideosMP(String userId, Integer sort, String stIdOne, String stIdTwo, Integer page, Integer limit) {
        if (page != null && limit != null){
            PageHelper.startPage(page,limit,false);
        }
        List<VideosVo> list = videosMapper.searchVideosMP(userId,sort,stIdOne,stIdTwo);
        return JsonData.success(list);
    }

    @Override
    public Map findBuyTeacherVideosByUserIdMP(String userId, String teacherId, Integer page, Integer limit) {
        if (page != null && limit != null){
            PageHelper.startPage(page,limit,false);
        }
        List<Videos> list = videosMapper.findBuyTeacherVideosByUserIdMP(userId,teacherId);
        return JsonData.success(list);
    }

    @Override
    public Map findTeacherAllVideosMP(String userId, String teacherId, Integer page, Integer limit) {
        if (page != null && limit != null){
            PageHelper.startPage(page,limit,false);
        }
        List<Videos> list = videosMapper.findTeacherAllVideosMP(teacherId);
        return JsonData.success(list);
    }

    @Override
    public Map findTeacherRecommendVideosMP(String userId, String teacherId, Integer page, Integer limit) {
        if (page != null && limit != null){
            PageHelper.startPage(page,limit,false);
        }
        List<Videos> list = videosMapper.findTeacherRecommendVideosMP(teacherId);
        return JsonData.success(list);
    }

    @Override
    public Map findRecommendVideosMoreMP(String searchName, Integer sort, String stIdOne, String stIdTwo, Integer page, Integer limit) {
        Map map = Maps.newHashMap();
        //课程列表
        if (page != null && limit != null){
            PageHelper.startPage(page,limit,false);
        }
        List<VideosVo> videosList = videosMapper.findVideosByType(searchName,sort,stIdOne,stIdTwo);

        map.put("videosList",videosList);
        return JsonData.success(map);
    }

    /**
     * @需求描述:查询讲师课程集业务逻辑层
     * @创建人:whh
     * @创建时间: 2019/11/13
     * @修改需求:
     * @修改人:
     * @修改时间:
     * @需求思路:
     */
    @Override
    public Map<String, Object> getTeacherVideo(Map<String, Object> map) {
        //验证参数
        UserInfoVo userInfoVo = (UserInfoVo)map.get("userInfoVo");
        map.put("userId",userInfoVo.getUserId());
        String str = AppUtil.checkIsNull(map);
        if (!str.equals(Const.SUCCESS_CODE_STR)) {
            return JsonData.fail(Const.parameterError(str));
        }

        userInfoVo.setIsTeacher(2);
        List<UserInfo> userInfos =  userInfoMapper.select(userInfoVo);
        if (0 == userInfos.size()){
            return JsonData.fail("讲师信息不存在");
        }

        //查询课程结果集
        VideosVo videosVo = new VideosVo();
        videosVo.setUserId(userInfoVo.getUserId());
        videosVo.setCheckStatus(1);
        videosVo.setIsPublish(1);
        videosVo.setIsDel(0);
        List<Videos> videos =videosMapper.select(videosVo);
        for (Videos video : videos){
            VideosItemVo videosItemVo = new VideosItemVo();
            videosItemVo.setVideoId(video.getVideoId());
            Integer videoItemCount = videosItemMapper.selectCount(videosItemVo);
            video.setVideoItemCount(videoItemCount);
        }
        return JsonData.success(videos,Const.OPREATE_MSG_SUCCESS);
    }

    @Override
    public Map addVideoItem(String userId, String videosId, String videosItemJson) {
//        //添加视频，要将发布的视频状态不修改,只是新添加未通过的不能看
//        Videos videos = new Videos();
//        videos.setVideoId(videosId);
//        videos.setIsPublish(0);
//        videosMapper.updateByPrimaryKeySelective(videos);

        List<VideosItem> videosItemList = JsonUtil.string2Obj(videosItemJson, new TypeReference<List<VideosItem>>() {});
        for (VideosItem videosItem : videosItemList) {
            videosItem.setVideoStatus(0);
            videosItem.setVideoItemId(AppUtil.uuid());
            videosItem.setCreateTime(new Date());
            videosItem.setIsTop(0);
        }

        int i = videosItemMapper.saveBatch(videosItemList);
        return JsonData.returnMap(i);
    }

    @Override
    public Map publish(String userId, String videosId) {
        //判断该视频是不是自己的
        Videos model = new Videos();
        model.setUserId(userId);
        model.setVideoId(videosId);
        int i = videosMapper.selectCount(model);
        if (i == 0){
            return JsonData.returnMap(500,"只能操作自己发布的课程");
        }
        Videos videos = new Videos();
        videos.setVideoId(videosId);
        videos.setIsPublish(1);
        int j = videosMapper.updateByPrimaryKeySelective(videos);
        return JsonData.returnMap(j);
    }

    @Override
    public Map updateNameOrUrl(String userId, Integer flag, String videoItemId, String videoItemName, String videoUrl, Double videoItemSize, String videoId) {
        //添加视频，要将发布的视频状态不修改,只是新添加未通过的不能看
//        Videos videos = new Videos();
//        videos.setVideoId(videoId);
//        videos.setIsPublish(0);
//        videosMapper.updateByPrimaryKeySelective(videos);

        //只能修改自己的视频
        int i = videosItemMapper.isMyVideos(userId,videoItemId);
        if (i == 0){
            return JsonData.returnMap(500,"只能修改自己发布的视频");
        }

        VideosItem videosItem = new VideosItem();
        videosItem.setVideoItemId(videoItemId);
        videosItem.setVideoStatus(0);
        videosItem.setCreateTime(new Date());

        // 1.修改名称 2.修改视频
        if (flag==1){
            videosItem.setVideoItemName(videoItemName);
        }else if (flag==2){
            videosItem.setVideoUrl(videoUrl);
            videosItem.setVideoItemSize(videoItemSize);
        }
        int j = videosItemMapper.updateByPrimaryKeySelective(videosItem);

        return JsonData.returnMap(j);
    }

    @Override
    public Map updateSort(String userId, String videoItemId, Integer sort) {
        //只能修改自己的视频
        int flag = videosItemMapper.isMyVideos(userId,videoItemId);
        if (flag == 0){
            return JsonData.returnMap(500,"只能修改自己发布的视频");
        }

        VideosItem videosItem = new VideosItem();
        videosItem.setVideoItemId(videoItemId);
        videosItem.setSort(sort);
        int i = videosItemMapper.updateByPrimaryKeySelective(videosItem);
        return JsonData.returnMap(i);
    }

    @Override
    public Map delByVideoId(String userId, String videosId) {
        //判断该视频是不是自己的
        Videos model = new Videos();
        model.setUserId(userId);
        model.setVideoId(videosId);
        int i = videosMapper.selectCount(model);
        if (i == 0){
            return JsonData.returnMap(500,"只能删除自己发布的课程");
        }
        //删除子视频
        VideosItem videosItem = new VideosItem();
        videosItem.setVideoId(videosId);
        videosItemMapper.delete(videosItem);
        //删除课程
        videosMapper.deleteByPrimaryKey(videosId);
        return JsonData.success(Const.OPREATE_MSG_SUCCESS);
    }

    @Override
    public Map delByVideosItemId(String userId, String videoItemId) {
        //只能删除自己的视频
        int flag = videosItemMapper.isMyVideos(userId,videoItemId);
        if (flag == 0){
            return JsonData.returnMap(500,"只能删除自己发布的视频");
        }

        int i = videosItemMapper.deleteByPrimaryKey(videoItemId);
        return JsonData.returnMap(i);
    }

    @Override
    public Map updateVideo(String userId, String videoId, String videoName, String teacherName, String stIdOne, String stIdTwo,
                           String videoDesc, String videoImg, Integer isFree, Double originalPrice, Double currentPrice,
                           Integer publishType) {
        //验证是否拉黑
        if (!StringUtils.equals("-1",userId) && StringUtils.isNotBlank(userId)) {
            User user = userMapper.selectByPrimaryKey(userId);
            if (user.getUserStatus() == 2) {
                return JsonData.returnMap(811, "您的账号已被锁定");
            }
        }

        //修改视频，必须是讲师才能发
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(userId);
        userInfo.setIsTeacher(2);
        int i = userInfoMapper.selectCount(userInfo);
        if (i==0){
            return JsonData.returnMap(500,"您不是讲师，不能修改视频");
        }

        Videos videos = new Videos();
        videos.setVideoId(videoId);
        videos.setUserId(userId);
        if (StringUtils.isNotBlank(videoName)){
            videos.setVideoName(videoName);
        }
        if (StringUtils.isNotBlank(teacherName)){
            videos.setTeacherName(teacherName);
        }
        if (StringUtils.isNotBlank(stIdOne)){
            videos.setStIdOne(stIdOne);
        }
        if (StringUtils.isNotBlank(stIdTwo)){
            videos.setStIdTwo(stIdTwo);
        }
        if (StringUtils.isNotBlank(videoDesc)){
            videos.setVideoDesc(videoDesc);
        }
        if (StringUtils.isNotBlank(videoImg)){
            videos.setVideoImg(videoImg);
        }
        if (isFree != null){
            videos.setIsFree(isFree);
            if (isFree ==0){
                //0.否 1.是
                videos.setOriginalPrice(originalPrice);
                videos.setCurrentPrice(currentPrice);
            }
        }
        if (publishType != null){
            videos.setPublishType(publishType);
        }
        videos.setCheckStatus(0);
        videos.setIsPublish(0);
        videos.setUpdateTime(new Date());
        videosMapper.updateByPrimaryKeySelective(videos);
        Map map = Maps.newHashMap();
        map.put("videos",videos);
        return JsonData.success(map);
    }

    @Override
    public Map noPass(Videos videos) {
        VideosItem vo = new VideosItem();
        vo.setVideoId(videos.getVideoId());
        int count1 = videosItemMapper.selectCount(vo);

        vo.setVideoStatus(1);
        int count2 = videosItemMapper.selectCount(vo);
//        if (count1 > count2){
//            return JsonData.fail("请先审核子视频");
//        }
        videos.setCheckStatus(2);
        videos.setUpdateTime(new Date());
        int i = videosMapper.updateByPrimaryKeySelective(videos);
        return JsonData.returnMap(i);
    }

    @Override
    public Map pass(String videoId) {
        //查询所有视频数
        VideosItem vo = new VideosItem();
        vo.setVideoId(videoId);
        int count1 = videosItemMapper.selectCount(vo);

        vo.setVideoStatus(1);
        int count2 = videosItemMapper.selectCount(vo);
        if (count1 > count2){
            return JsonData.fail("请先审核子视频");
        }
        Videos videos = videosMapper.selectByPrimaryKey(videoId);
        Integer publishType = videos.getPublishType();

        //判断课程详情是否通过
        //判断通过的视频数和总视频数是否相等，相等就修改发布状态
        if (publishType==1){
            //发布类型 1.审核通过后立即发布 2.先提交本次审核
            if (count1==count2){
               //全部审核通过，修改状态
               videos.setIsPublish(1);

            }
        }
        //审核状态 0.审核中 1. 通过 2.不通过
        videos.setCheckStatus(1);
        videos.setUpdateTime(new Date());
        videosMapper.updateByPrimaryKeySelective(videos);
        return JsonData.success();
    }

    @Override
    public Map updateType(Videos videos) {
        int i = videosMapper.updateByPrimaryKeySelective(videos);
        return JsonData.returnMap(i);
    }

    @Override
    public Map findVideosDetailByVideoItemId(String userId, String videoItemId) {
        Map map = Maps.newHashMap();

        //当前视频详情
        VideosItem videosItem = videosItemMapper.selectByPrimaryKey(videoItemId);
        if (null == videosItem){
            return JsonData.fail("视频不存在");
        }

        //视频介绍
        VideosVo videosVo = videosMapper.findByVideoId(videosItem.getVideoId());
        if (null == videosVo){
            return JsonData.fail("课程不存在");
        }
        //讲师详情
        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setUserId(videosItem.getUserId());
        userInfoVo = userInfoMapper.findUserInfo(userInfoVo);

        VideosItem model = new VideosItem();
        model.setVideoId(videosItem.getVideoId());
        model.setVideoStatus(1);
        PageHelper.orderBy("sort asc");
        List<VideosItem> videosItemList = videosItemMapper.select(model);

        BuyVideos buyVideos = new BuyVideos();
        buyVideos.setVideosId(videosVo.getVideoId());
        buyVideos.setUserId(userId);
        int isBuy = buyVideosMapper.selectCount(buyVideos);

        map.put("isBuy",isBuy);
        map.put("videosItem",videosItem);
        map.put("videosVo",videosVo);
        map.put("userInfo",userInfoVo);
        map.put("videosItemList",videosItemList);
        return JsonData.success(map);
    }

    @Override
    public Map del(String videoId) {
        Videos videos = new Videos();
        videos.setVideoId(videoId);
        videos.setIsDel(1);
        int i = videosMapper.updateByPrimaryKeySelective(videos);
        return JsonData.returnMap(i);
    }

    @Override
    public Map up(String videoId) {
        Videos videos = new Videos();
        videos.setVideoId(videoId);
        videos.setIsDel(0);
        int i = videosMapper.updateByPrimaryKeySelective(videos);
        return JsonData.returnMap(i);
    }

    @Override
    public Map updateVideoItem(String userId, String videoItemId, String videoItemName, Double videoItemSize, String videoUrl, Integer sort, String videoId) {
        //验证是否拉黑
        if (!StringUtils.equals("-1",userId) && StringUtils.isNotBlank(userId)) {
            User user = userMapper.selectByPrimaryKey(userId);
            if (user.getUserStatus() == 2) {
                return JsonData.returnMap(811, "您的账号已被锁定");
            }
        }

        //修改播单中的单个视频
        VideosItem item = new VideosItem();
        item.setVideoItemId(videoItemId);
        if (StringUtils.isNotBlank(videoItemName)){
            item.setVideoItemName(videoItemName);
        }
        if (videoItemSize != null){
            item.setVideoItemSize(videoItemSize);
        }
        if (StringUtils.isNotBlank(videoUrl)){
            item.setVideoUrl(videoUrl);
        }
        if (sort != null){
            item.setSort(sort);
        }
        if (StringUtils.isNotBlank(videoId)){
            item.setVideoId(videoId);
        }
        //修改过的就要将审核状态变成未审核
        item.setVideoStatus(0);
        int i = videosItemMapper.updateByPrimaryKeySelective(item);
        return JsonData.returnMap(i);
    }

    /**
     * @需求描述:查看课程讲师简介业务逻辑层
     * @创建人:whh
     * @创建时间: 2019/11/13
     * @修改需求:
     * @修改人:
     * @修改时间:
     * @需求思路:
     */
    @Override
    public Map<String, Object> getVideoTeacher(Map<String, Object> map) {
        VideosVo videosVo = (VideosVo)map.get("videosVo");
        if (null == videosVo.getVideoId() || "" == videosVo.getVideoId()){
            return JsonData.fail(Const.PARA_IS_NULL);
        }


        UserInfoVo userInfoVo = videosMapper.getVideoTeacher(videosVo);

        Videos videos = videosMapper.findByVideoId(videosVo.getVideoId());


        VideosItem item = new VideosItem();
        item.setVideoId(videosVo.getVideoId());
        item.setVideoStatus(1);
        PageHelper.orderBy("sort asc");
        List<VideosItem> videosItemList = videosItemMapper.select(item);
        if (videosItemList.size()>0 && null ==  videos.getTryVideoItemId()){
            item = videosItemList.get(0);
        }
        if (videosItemList.size()>0 && null != videos.getTryVideoItemId()){
            for (VideosItem videosItem : videosItemList){
                if (videosItem.getVideoItemId() == videos.getTryVideoItemId()){
                    item = videosItem;
                    break;
                }
            }
        }

        map.clear();
        map.put("videosItemList",videosItemList);
        map.put("userInfoVo",userInfoVo);
        map.put("videos",videos);
        map.put("tryVideoItem",item);
        return JsonData.success(map,Const.OPREATE_MSG_SUCCESS);
    }

    @Override
    public Map findVideosByVideoId(String userId, String videoId) {
        Map map  = Maps.newHashMap();

        VideosVo videos = videosMapper.findByVideoId(videoId);

        VideosItem item = new VideosItem();
        item.setVideoId(videoId);
        PageHelper.orderBy("sort asc");
        List<VideosItem> videosItemList = videosItemMapper.select(item);

        BuyVideos buyVideos = new BuyVideos();
        buyVideos.setUserId(userId);
        buyVideos.setVideosId(videoId);
        int isBuy = buyVideosMapper.selectCount(buyVideos);


        PlayRecordSon playRecordSon = null;
        PlayRecordSon record = new PlayRecordSon();
        record.setUserId(userId);
        record.setVideosId(videoId);
        PageHelper.orderBy("create_time desc");
        List<PlayRecordSon> select = playRecordSonMapper.select(record);
        if (CollectionUtils.isNotEmpty(select)) {
            playRecordSon = select.get(0);
        }

        map.put("isBuy",isBuy);
        map.put("videos",videos);
        map.put("videosItemList",videosItemList);
        map.put("playRecordSon",playRecordSon);
        return JsonData.success(map);
    }

    @Override
    public Map findVideosByType(String searchName, Integer sort, String stIdOne, String stIdTwo, Integer page, Integer limit) {
        Map map = Maps.newHashMap();

        int totalCount = videosMapper.findVideosByType(searchName, sort, stIdOne, stIdTwo).size();
        //课程列表
        if (page != null && limit != null){
            PageHelper.startPage(page,limit,false);
        }
        List<VideosVo> videoslist = videosMapper.findVideosByType(searchName,sort,stIdOne,stIdTwo);

        //推荐课程（不受上面控制）4条
        PageHelper.startPage(1,4,false);
        List<VideosVo> recommentvideosList = videosMapper.recommentVideos();

        map.put("totalCount",totalCount);
        map.put("videoslist",videoslist);
        map.put("recommentvideosList",recommentvideosList);
        return JsonData.success(map);
    }

    @Override
    public Map searchVideos(String searchName, Integer page, Integer limit) {
        Map map = Maps.newHashMap();
        int totalCount = videosMapper.searchVideos(searchName).size();
        if (page != null && limit != null){
            PageHelper.startPage(page,limit,false);
        }
        List<VideosVo> list = videosMapper.searchVideos(searchName);
        map.put("totalCount",totalCount);
        map.put("list",list);
        return JsonData.success(map);
    }

    @Override
    public Map saveVideos(String userId, String videoName, String teacherName, String stIdOne, String stIdTwo, String videoDesc, String videoImg,
                          Integer isFree, Double originalPrice, Double currentPrice, Integer publishType, String videosItemJson) {
        //验证是否拉黑
        if (!StringUtils.equals("-1",userId) && StringUtils.isNotBlank(userId)) {
            User user = userMapper.selectByPrimaryKey(userId);
            if (user.getUserStatus() == 2) {
                return JsonData.returnMap(811, "您的账号已被锁定");
            }
        }

        //发布视频，必须是讲师才能发
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(userId);
        userInfo.setIsTeacher(2);
        int i = userInfoMapper.selectCount(userInfo);
        if (i==0){
            return JsonData.returnMap(500,"您不是讲师，不能发布视频");
        }

        Videos videos = new Videos();
        String videosId = AppUtil.uuid();
        videos.setVideoId(videosId);
        videos.setUserId(userId);
        videos.setVideoName(videoName);
        videos.setTeacherName(teacherName);
        videos.setStIdOne(stIdOne);
        videos.setStIdTwo(stIdTwo);
        videos.setVideoDesc(videoDesc);
        videos.setVideoImg(videoImg);
        videos.setIsFree(isFree);
        videos.setPublishType(publishType);
        videos.setIsPublish(0);
        videos.setUpdateTime(new Date());
        if (isFree ==0){
            //0.否 1.是
            videos.setOriginalPrice(originalPrice);
            videos.setCurrentPrice(currentPrice);
        }
        videos.setCreateTime(new Date());

        List<VideosItem> videosItemList = JsonUtil.string2Obj(videosItemJson, new TypeReference<List<VideosItem>>() {
        });
        for (VideosItem videosItem : videosItemList) {
            videosItem.setVideoId(videosId);
            videosItem.setVideoStatus(0);
            videosItem.setVideoItemId(AppUtil.uuid());
            videosItem.setCreateTime(new Date());
            videosItem.setIsTop(0);
        }

        //记录上传记录
        HistoryUploadVideos uploadVideos = new HistoryUploadVideos();
        uploadVideos.setHuvId(AppUtil.uuid());
        uploadVideos.setCreateTime(new Date());
        uploadVideos.setUploadCount(videosItemList.size());
        uploadVideos.setUserId(userId);
        uploadVideos.setVideoId(videosId);

        uploadVideosMapper.insertSelective(uploadVideos);
        videosMapper.insertSelective(videos);
        videosItemMapper.saveBatch(videosItemList);

        Map map = Maps.newHashMap();
        map.put("videos",videos);
        map.put("videosItemList",videosItemList);
        return JsonData.success(map);
    }

    @Override
    public Map findByWhere(String videoName, String stIdOne, String stIdTwo, String stIdThree, Integer page, Integer limit, Integer checkStatus, Integer isDel) {
        int count = videosMapper.findByWhere(videoName, stIdOne, stIdTwo, stIdThree,checkStatus, isDel).size();

        if (page != null && limit != null) {
            PageHelper.startPage(page, limit, false);
            PageHelper.orderBy("create_time desc");
        }
        List<VideosVo> videosVoList = videosMapper.findByWhere(videoName, stIdOne, stIdTwo, stIdThree,checkStatus,isDel);
        return JsonData.returnLayuiMap(videosVoList, count);
    }

    @Override
    public Map uploadVideos(String userId, String createId, Integer isCreateVideos, String videosId, String videoName, String teacherName,
                            String stIdOne, String stIdTwo, String videoDesc, String videoImg, Integer isFree, Double originalPrice,
                            Double currentPrice, Integer publishType, List<VideosItem> videosItemList, List<VideosInfoVo> videosInfoList, String alreadyVideosItemList) {
        //验证是否拉黑
        if (!StringUtils.equals("-1",userId) && StringUtils.isNotBlank(userId)) {
            User user = userMapper.selectByPrimaryKey(userId);
            if (null == user){
                return JsonData.fail("用户信息不存在");
            }
            if (user.getUserStatus() == 2) {
                return JsonData.returnMap(811, "您的账号已被锁定");
            }
        }
        //发布视频，必须是讲师才能发
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(userId);
        userInfo.setIsTeacher(2);
        int i = userInfoMapper.selectCount(userInfo);
        if (i==0){
            User user = userMapper.selectByPrimaryKey(createId);
            if(null != user && user.getUserType() == 1){
                return JsonData.returnMap(500,"您不是讲师，不能发布视频");
            }
        }
        Map map = Maps.newHashMap();

        /*创建课程*/
        Videos videos = new Videos();
        if(null != isCreateVideos && isCreateVideos == 1){
            // 1 创建课程
            videosId = AppUtil.uuid();
            videos.setVideoId(videosId);
            videos.setUserId(userId);
            videos.setVideoName(videoName);
            videos.setTeacherName(teacherName);
            videos.setStIdOne(stIdOne);
            videos.setStIdTwo(stIdTwo);
            videos.setVideoDesc(videoDesc);
            videos.setVideoImg(videoImg);
            videos.setIsFree(isFree);
            videos.setPublishType(publishType);
            videos.setIsPublish(0);
            videos.setCreateId(createId);
            videos.setUpdateTime(new Date());
            if (isFree ==0){
                //0.否 1.是
                videos.setOriginalPrice(originalPrice);
                videos.setCurrentPrice(currentPrice);
            }
            videos.setCreateTime(new Date());
            videos.setCheckStatus(0);
            videosMapper.insertSelective(videos);
            /*如果创建课程的时候上传了资料*/
            if(null != videosInfoList && 0 != videosInfoList.size()){
                for (VideosInfoVo videosInfo : videosInfoList) {
                    videosInfo.setVideosInfoId(AppUtil.uuid());
                    videosInfo.setStatus(0);
                    videosInfo.setVideoId(videosId);
                    videosInfo.setCreateId(createId);
                    videosInfo.setDownCount(0);
                    videosInfo.setCreateTime(new Date());
                    videosInfoMapper.insertSelective(videosInfo);
                }
            }
        }else if (isCreateVideos == 2){
            //2 添加已有课程
            //修改视频审核状态
            Videos videos1 = new Videos();
            videos1.setVideoId(videosId);
            videos1.setCreateTime(new Date());
            videosMapper.updateByPrimaryKeySelective(videos1);
            //添加到已有课程，原有视频排序修改
            if (StringUtils.isNotBlank(alreadyVideosItemList) && isCreateVideos == 2){
                List<VideosItem> videosItems = JsonUtil.string2Obj(alreadyVideosItemList, new TypeReference<List<VideosItem>>() {
                });
                videosItemMapper.updateRelationVideosId(videosId,videosItems);
            }
        }

        /*新上传的视频遍历视频插入*/
        if(null != videosItemList && 0 != videosItemList.size()){
            for (VideosItem videosItem : videosItemList) {
                if(null != videosId){
                    videosItem.setVideoId(videosId);
                }
                videosItem.setUserId(userId);
                videosItem.setVideoStatus(0);
                videosItem.setVideoItemId(AppUtil.uuid());
                videosItem.setCreateTime(new Date());
                videosItem.setIsTop(0);
            }
            videosItemMapper.saveBatch(videosItemList);
        }


        //记录上传记录
        HistoryUploadVideos uploadVideos = new HistoryUploadVideos();
        uploadVideos.setHuvId(AppUtil.uuid());
        uploadVideos.setCreateTime(new Date());
        uploadVideos.setUploadCount(videosItemList.size());
        uploadVideos.setUserId(userId);
        uploadVideos.setVideoId(videosId);
        uploadVideosMapper.insertSelective(uploadVideos);
        map.put("videos",videos);
        map.put("videosItemList",videosItemList);
        map.put("videosItemList",videosInfoList);
        return JsonData.success(map);
    }

    @Override
    public Map addUsedVideo(String userId, String videoId, String videoItemIdJson) {
        //只能添加自己的课程
        Videos videos = videosMapper.selectByPrimaryKey(videoId);
        if (!StringUtils.equals(userId,videos.getUserId())){
            return JsonData.fail("只能添加自己的课程");
        }
        List<VideosItem> videosItems = JsonUtil.string2Obj(videoItemIdJson, new TypeReference<List<VideosItem>>() {
        });
        videosItemMapper.updateRelationVideosId(videoId,videosItems);
        return JsonData.success();
    }

    @Override
    public Map getVideoItems(String userId, Integer videoStatus, Integer page, Integer limit) {
        VideosItemVo videosItem = new VideosItemVo();
        videosItem.setVideoStatus(videoStatus);
        videosItem.setUserId(userId);
        if (page != null && limit != null){
            PageHelper.startPage(page,limit,false);
        }
        List<VideosItem> videosItemList = this.videosItemMapper.selectVideoItemInfo(videosItem);
        Integer videosItemCount = this.videosItemMapper.selectVideoItemInfoCount(videosItem);
        Map map = Maps.newHashMap();
        map.put("videosItemList",videosItemList);
        map.put("videosItemCount",videosItemCount);
        return JsonData.success(map);
    }

//    @Override
//    public Map getVideos(String userId, Integer page, Integer limit) {
//        List<VideosItem> videosItems;
//        if (page != null && limit != null){
//            PageHelper.startPage(page,limit,false);
//        }
//
//        PageHelper.orderBy("is_top desc,create_time desc");
//        List<Videos> videosList = videosMapper.getCheckingAndPassVideo(userId);
//        for (Videos videos : videosList){
//            VideosItemVo videosItemVo = new VideosItemVo();
//            videosItemVo.setVideoId(videos.getVideoId());
//            videosItems = videosItemMapper.select(videosItemVo);
//            Integer videoItemCount = videosItems.size();
//            videos.setVideoItemCount(videoItemCount);
//        }
//        Integer videosListCount = this.videosMapper.getCheckingAndPassVideo(userId).size();
//        Map map = Maps.newHashMap();
//        map.put("videosList",videosList);
//        map.put("videosListCount",videosListCount);
//        return JsonData.success(map);
//    }



    /**
     * @需求描述:发布课程
     * @创建人:moke
     * @创建时间: 2019/11/22 11:00
     * @修改需求:
     * @修改人:
     * @修改时间:
     * @需求思路:
     */
    @Override
    public Map issueVideo(String videoId) {
        /*查询需要更新的课程*/
        Videos videos = this.videosMapper.selectByPrimaryKey(videoId);
        /*设置改课程为发布状态*/
        videos.setIsPublish(1);
        int i = this.videosMapper.updateByPrimaryKeySelective(videos);
        return JsonData.returnMap(i);
    }

    /**
     * @需求描述: 重新编辑课程
     * @创建人:moke
     * @创建时间: 2019/11/22 11:00
     * @修改需求:
     * @修改人:
     * @修改时间:
     * @需求思路:
     */
    @Override
    public Map reeditVideo(String videosId, String videoName, String stIdOne, String stIdTwo, String videoDesc,
                           String videoImg, Integer isFree, Double originalPrice, Double currentPrice, Integer publishType,
                           List<VideosItem> videosItemList, List<VideosInfoVo> videosInfoList) {
        Videos videos = this.videosMapper.selectByPrimaryKey(videosId);
        /*如果参数不为空更新*/
        if(StringUtils.isNotEmpty(videoName)){
            videos.setVideoName(videoName);
        }
        if(StringUtils.isNotEmpty(stIdOne)){
            videos.setStIdOne(stIdOne);
        }
        if(StringUtils.isNotEmpty(stIdTwo)){
            videos.setStIdTwo(stIdTwo);
        }
        if(StringUtils.isNotEmpty(videoDesc)){
            videos.setVideoDesc(videoDesc);
        }
        if(StringUtils.isNotEmpty(videoImg)){
            videos.setVideoImg(videoImg);
        }

        if(null != isFree){
            videos.setIsFree(isFree);
        }
        if(null != originalPrice){
            videos.setOriginalPrice(originalPrice);
        }
        if(null != currentPrice){
            videos.setCurrentPrice(currentPrice);
        }
        if(null != publishType){
            videos.setPublishType(publishType);
        }
        videos.setCheckStatus(0);
        videos.setCreateTime(new Date());
        int i = this.videosMapper.updateByPrimaryKeySelective(videos);
        List<VideosItem> videosItems = new ArrayList<>();
        if(videosItemList.size() != 0){
            for (VideosItem videosItem : videosItemList) {
                if(null != videosItem.getVideoItemId()){
                    videosItem.setUpdateTime(new Date());
                    videosItemMapper.updateByPrimaryKeySelective(videosItem);
                    videosItems.add(videosItem);
                }else{
                    /*不存在的新增*/
                    videosItem.setVideoId(videosId);
                    videosItem.setUserId(videos.getUserId());
                    videosItem.setVideoStatus(0);
                    videosItem.setVideoItemId(AppUtil.uuid());
                    videosItem.setCreateTime(new Date());
                    videosItem.setIsTop(0);
                    this.videosItemMapper.insertSelective(videosItem);
                    videosItems.add(videosItem);
                }
            }
        }
        /*如果创建课程的时候上传了资料*/
        List<VideosInfo> videosInfos = new ArrayList<>();
        if(videosInfoList.size() != 0){
            //删除资料
            VideosInfoVo videosInfoVo = new VideosInfoVo();
            videosInfoVo.setVideoId(videosId);
            this.videosInfoMapper.delete(videosInfoVo);
            /*上传了资料*/
            if(0 != videosInfoList.size()){
                for (VideosInfoVo videosInfo : videosInfoList) {
                    videosInfo.setVideosInfoId(AppUtil.uuid());
                    videosInfo.setStatus(1);
                    videosInfo.setVideoId(videosId);
                    videosInfo.setCreateTime(new Date());
                    videosInfoMapper.insertSelective(videosInfo);
                    videosInfos.add(videosInfo);
                }

            }
        }
        //记录上传记录
        HistoryUploadVideos uploadVideos = new HistoryUploadVideos();
        uploadVideos.setHuvId(AppUtil.uuid());
        uploadVideos.setCreateTime(new Date());
        uploadVideos.setUploadCount(videosItems.size());
        uploadVideos.setUserId(videosId);
        uploadVideos.setVideoId(videosId);
        uploadVideosMapper.insertSelective(uploadVideos);
        Map map = Maps.newHashMap();
        map.put("code",Const.SUCCESS_CODE);
        map.put("videos",videos);
        map.put("videosItemList",videosItems);
        map.put("videosInfoList",videosInfos);

        return JsonData.returnMap(i);
    }

    /**
     * @需求描述: 查看全部课程,审核通过的
     * @创建人:moke
     * @创建时间: 2019/11/22 11:01
     * @修改需求:
     * @修改人:
     * @修改时间:
     * @需求思路:
     */
    @Override
    public Map getAllVideos(String userId, Integer page, Integer limit) {
        if (page != null && limit != null){
            PageHelper.startPage(page,limit);
        }
        List<Videos> list = videosMapper.findVideosByUserId(userId);
        PageInfo info = new PageInfo(list);
        return JsonData.success(info);
    }

    /**
     * @需求描述: 查看课程信息
     * @创建人:moke
     * @创建时间: 2019/11/22 11:01
     * @修改需求:
     * @修改人:
     * @修改时间:
     * @需求思路:
     */
    @Override
    public Map getVideosMessage(String videoId) {
        /*查看课程详情*/
        VideosVo Videos = this.videosMapper.findByVideoId(videoId);
        /*查看课程下的视频*/
        VideosItem item = new VideosItem();
        item.setVideoId(videoId);
        PageHelper.orderBy("sort asc");
        List<VideosItem> videosItemList = videosItemMapper.select(item);
        /*查看课程下的资料*/
        VideosInfoVo videosInfoVo = new VideosInfoVo();
        videosInfoVo.setVideoId(videoId);
        videosInfoVo.setStatus(1);
        PageHelper.orderBy("video_info_sort asc");
        List<VideosInfoVo> videosInfoVoList = this.videosInfoMapper.select(videosInfoVo);
        Map map = Maps.newHashMap();
        map.put("code", Const.SUCCESS_CODE);
        map.put("Videos",Videos);
        map.put("videosItemList",videosItemList);
        map.put("videosInfoVoList",videosInfoVoList);
        return map;
    }


    /**
     * @需求描述:指定课程试看视频
     * @创建人:whh
     * @创建时间: 2019/11/25
     * @修改需求:
     * @修改人:
     * @修改时间:
     * @需求思路:
     */
    @Override
    public Map addTryVideoItemsToVideoId(String videoItemId, String videoId) {
        Videos videos =  videosMapper.selectByPrimaryKey(videoId);
        if (null == videos){
            return JsonData.fail("课程不存在");
        }
        videos.setTryVideoItemId(videoItemId);
        Integer result = videosMapper.updateByPrimaryKey(videos);
        if (1 == result){
            return JsonData.success(result,Const.OPREATE_MSG_SUCCESS);
        }
        return JsonData.fail(Const.OPREATE_MSG_ERROR);
    }


    @Override
    public Map createUpdateVideo(String userId, String videoName, String teacherName, String stIdOne,
                                 String stIdTwo, String videoDesc, String videoImg, Integer isFree, Double originalPrice, Double currentPrice, Integer publishType) {

        Map map = new HashMap();
        //补齐新增实体
        Videos videos = new Videos();

        videos.setUserId(userId);
        videos.setVideoName(videoName);
        videos.setTeacherName(teacherName);
        List<Videos> videosList = videosMapper.select(videos);

        if (0 == videosList.size()){
            videos.setVideoId(AppUtil.uuid());
            videos.setStIdOne(stIdOne);
            videos.setStIdTwo(stIdTwo);
            videos.setVideoDesc(videoDesc);
            videos.setVideoImg(videoImg);
            videos.setIsFree(isFree);
            videos.setOriginalPrice(originalPrice);
            videos.setCurrentPrice(currentPrice);
            videos.setPublishType(publishType);
            videos.setIsPublish(0);
            if (publishType == 1){
                videos.setIsPublish(1);
            }
            videos.setIsRecomment(0);
            videos.setCreateTime(new Date());
            videos.setUpdateTime(new Date());
            videos.setCreateId(userId);
            videos.setCheckStatus(1);
            videos.setIsDel(0);
            videos.setUpdateTime(new Date());
            Integer result =  videosMapper.insertSelective(videos);
            if (1 == result){
                map.put("videoId",videos.getVideoId());
                return map;
            }
        }
        map.put("videoId",videosList.get(0).getVideoId());
        return map;
    }

    @Override
    public Map recordNumbersOfVideo(String videosId,String videoItemId) {
        Videos videos = this.videosMapper.selectByPrimaryKey(videosId);
        if(null != videos){
            videos.setStudyCount(videos.getStudyCount() != null?videos.getStudyCount()+1:1);
            this.videosMapper.updateByPrimaryKeySelective(videos);

        }
        VideosItem videosItem = this.videosItemMapper.selectByPrimaryKey(videoItemId);
        if(null != videosItem){
            videosItem.setStudyCount(videosItem.getStudyCount() != null?videos.getStudyCount()+1:1);
            this.videosItemMapper.updateByPrimaryKeySelective(videosItem);
        }
        return JsonData.success();
    }

    @Override
    public Map soldOutVideos(String videosId) {
        Videos videos = this.videosMapper.selectByPrimaryKey(videosId);
        if(null != videos){
            videos.setIsDel(1);
            videos.setIsTop(0);
            int i = this.videosMapper.updateByPrimaryKeySelective(videos);
            return JsonData.returnMap(i);
        }

        return JsonData.fail("改视频没有添加到课程中");
    }
}
